package com.sux.demo;

import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

@ChannelHandler.Sharable
public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {

    private ChannelGroup channelGroup;

    public WebSocketServerHandler() {
        channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    }

    public ChannelGroup getChannelGroup() {
        return channelGroup;
    }

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof PongWebSocketFrame) {
            System.out.println(simpleDateFormat.format(new Date()) + " 收到客户端" + ctx.channel().remoteAddress() + "发来的心跳：PONG");
        }

        if (msg instanceof TextWebSocketFrame) {
            TextWebSocketFrame frame = (TextWebSocketFrame) msg;
            System.out.println(simpleDateFormat.format(new Date()) + " 收到客户端" + ctx.channel().remoteAddress() + "发来的消息：" + frame.text());

            /* // 测试转发消息
            for (Channel channel : channelGroup) {
                if (!ctx.channel().id().toString().equals(channel.id().toString())) {
                    channel.writeAndFlush(new TextWebSocketFrame(Unpooled.copiedBuffer(frame.text(), CharsetUtil.UTF_8)));
                    System.out.println("服务端向客户端 " + channel.id().toString() + " 转发消息：" + frame.text());
                }
            } */
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        channelGroup.add(ctx.channel());
        System.out.println(simpleDateFormat.format(new Date()) + " 客户端" + ctx.channel().id().toString() + "已连接");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        channelGroup.remove(ctx.channel());
        System.out.println(simpleDateFormat.format(new Date()) + " 客户端" + ctx.channel().id() + "已断开, 服务端已移除该客户端");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}
